﻿


CREATE PROCEDURE [dbo].[exbug_GenereazaExecutieCheltuieli]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@Data datetime,
	@IDDepartament int,
	@IDJurnal int
AS
BEGIN
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO [ExecutieCheltuieli]
           ([ArtAl]
           ,[Data]
           ,[Valoare]
           ,[CodUnitate]
           ,[IDJurnal]
           ,[IDDepartament])
     SELECT [ArtAl],@Data,0,@CodUnitate,@IDJurnal,@IDDepartament  FROM [ArticoleAliniate] a WHERE [CodUnitate]=@CodUnitate and a.ExecutieCheltuieli=1 
     AND NOT EXISTS(SELECT * FROM [ExecutieCheltuieli] e WHERE a.ArtAl= e.ArtAl AND a.CodUnitate=e.CodUnitate and MONTH(e.Data)=Month(@Data)and YEAR(e.Data)=YEAR(@Data)  and e.IDDepartament = @IDDepartament
     AND e.IDJurnal = @IDJurnal)
     
     DELETE FROM [ExecutieCheltuieli] WHERE 
     NOT EXISTS(SELECT * FROM [ArticoleAliniate] a  WHERE [ExecutieCheltuieli].ArtAl= a.ArtAl AND a.CodUnitate=@CodUnitate AND a.ExecutieCheltuieli=1)
      and MONTH([ExecutieCheltuieli].Data)=Month(@Data) and YEAR([ExecutieCheltuieli].Data)=YEAR(@Data) and [ExecutieCheltuieli].IDDepartament = @IDDepartament
     AND [ExecutieCheltuieli].IDJurnal = @IDJurnal AND [ExecutieCheltuieli].CodUnitate=@CodUnitate

END